import { FamousPersonInfo, getFamousPersonInfo } from '@/services/FamousPersonService';
import {
  CalendarOutlined,
  HeartOutlined,
  HistoryOutlined,
  MessageOutlined,
  StarOutlined,
  TrophyOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { Card, Col, Image, Row, Tag, message, Timeline, Modal, Button, Typography } from 'antd';
import pinyin from 'pinyin';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { getMilestoneList, Milestone } from '@/services/MilestoneService';
import { getQuoteListFront } from '@/services/QuoteService';
import { famousPersonId } from '@/services';
import { getHonorPage, HonorInfo } from '@/services/HonorService';
import dayjs from 'dayjs';
import ReactPlayer from 'react-player';
import type { Quote } from '@/services/QuoteService';

const { Title } = Typography;

const ProfilePage: React.FC = () => {
  const [basicInfo, setBasicInfo] = useState<FamousPersonInfo>();
  const [milestones, setMilestones] = useState<Milestone[]>([]);
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [quoteLoading, setQuoteLoading] = useState(false);
  const [quotePagination, setQuotePagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [videoModalVisible, setVideoModalVisible] = useState(false);
  const [currentVideo, setCurrentVideo] = useState('');
  const [honors, setHonors] = useState<HonorInfo[]>([]);
  const [honorLoading, setHonorLoading] = useState(false);
  const [honorPagination, setHonorPagination] = useState({
    current: 1,
    pageSize: 6,
    total: 0,
    hasMore: true,
  });

  // 生成拼音的函数
  const generatePinyin = (name: string) => {
    if (!name) return '';
    return pinyin(name, {
      style: pinyin.STYLE_NORMAL,
      heteronym: false,
    }).map((p: string[]) => p[0]).join(' ');
  };

  // 获取基本信息
  useEffect(() => {
    const fetchBasicInfo = async () => {
      try {
        const data = await getFamousPersonInfo(famousPersonId);  // 假设ID为1
        const pinyinStr = generatePinyin(data.name);
        console.log(data);
        setBasicInfo({
          ...data,
          pinyin: pinyinStr
        });
      } catch (error) {
        message.error('获取信息失败');
      }
    };

    fetchBasicInfo();
  }, []);

  // 获取里程碑数据
  useEffect(() => {
    const fetchMilestones = async () => {
      try {
        const data = await getMilestoneList(famousPersonId); // 假设ID为1
        setMilestones(data);
      } catch (error) {
        message.error('获取里程碑信息失败');
      }
    };

    fetchMilestones();
  }, []);

  // 处理视频点击
  const handleVideoClick = (videoId: string) => {
    setCurrentVideo(`/api/file/play/${videoId}`);
    setVideoModalVisible(true);
  };

  // 处理多种分隔的字符串转换为数组
  const splitString = (str: string = '') => {
    const normalizedStr = str.replace(/，/g, ',').replace(/、/g, ',');
    return normalizedStr.split(',').map(item => item.trim()).filter(Boolean);
  };

  // 添加获取语录的函数
  const fetchQuotes = async (page = 1) => {
    try {
      setQuoteLoading(true);
      const response = await getQuoteListFront({
        pageCurrent: page,
        pageSize: quotePagination.pageSize,
        famousPersonId: 1,
      });
      
      if (page === 1) {
        setQuotes(response.list);
      } else {
        setQuotes(prev => [...prev, ...response.list]);
      }
      
      setQuotePagination(prev => ({
        ...prev,
        current: page,
        total: response.totalCount,
      }));
    } catch (error) {
      message.error('获取语录失败');
    } finally {
      setQuoteLoading(false);
    }
  };

  // 在组件加载时获取语录
  useEffect(() => {
    fetchQuotes();
  }, []);

  // 添加加载荣誉数据的函数
  const loadHonors = async (page = honorPagination.current) => {
    try {
      setHonorLoading(true);
      const response = await getHonorPage({
        pageCurrent: page,
        pageSize: honorPagination.pageSize,
        famousPersonId,
      });
      
      if (page === 1) {
        setHonors(response.list);
      } else {
        setHonors(prev => [...prev, ...response.list]);
      }
      
      setHonorPagination(prev => ({
        ...prev,
        current: page,
        total: response.totalCount,
        hasMore: response.list.length === prev.pageSize,
      }));
    } catch (error) {
      message.error('获取荣誉数据失败');
    } finally {
      setHonorLoading(false);
    }
  };

  // 在 useEffect 中加载数据
  useEffect(() => {
    loadHonors(1);
  }, []);

  // 处理加载更多
  const handleLoadMoreHonors = () => {
    if (!honorLoading && honorPagination.hasMore) {
      loadHonors(honorPagination.current + 1);
    }
  };

  // 兴趣爱好数据 舞蹈、小提琴、钢琴
  const hobbies = [
    {
      name: '舞蹈',
      icon: '💃',
      description: '',
    },
    {
      name: '小提琴',
      icon: '🎻',
      description: '',
    },
    {
      name: '钢琴',
      icon: '🎹',
      description: '',
    }
    // ... 其他爱好数据
  ];

  // 修改生涯历程部分的渲染
  const renderMilestones = () => (
    <Timeline>
      {milestones.map((milestone) => (
        <Timeline.Item key={milestone.id}>
          <div className={styles.milestoneContent}>
            <div className={styles.date}>{milestone.eventDate}</div>
            <div className={styles.description}>
              {milestone.description}
            </div>
            
            {/* 图片展示区 */}
            {milestone.imageObjs?.length > 0 && (
              <div className={styles.imageGrid}>
                <Image.PreviewGroup>
                  {milestone.imageObjs.map((image) => (
                    <div key={image.id} className={styles.imageWrapper}>
                      <Image
                        src={`/api/file/play/${image.id}`}
                        alt={image.fileName}
                        className={styles.milestoneImage}
                      />
                    </div>
                  ))}
                </Image.PreviewGroup>
              </div>
            )}
            
            {/* 视频展示区 */}
            {milestone.videoObjs?.length > 0 && (
              <div className={styles.videoGrid}>
                {milestone.videoObjs.map((video) => (
                  <div key={video.id} className={styles.videoWrapper}>
                    <ReactPlayer
                      url={`/api/file/play/${video.id}`}
                      controls
                      width="100%"
                      height="100%"
                      config={{
                        file: {
                          attributes: {
                            controlsList: 'nodownload',
                            disablePictureInPicture: true,
                          },
                        },
                      }}
                    />
                  </div>
                ))}
              </div>
            )}
          </div>
        </Timeline.Item>
      ))}
    </Timeline>
  );

  // 修改Modal关闭处理函数
  const handleModalClose = () => {
    setVideoModalVisible(false);
  };

  // 修改荣誉卡片的渲染
  const renderHonors = () => (
    <Card className={styles.section}>
      <div className={styles.sectionTitle}>
        <TrophyOutlined />
        <span>荣誉殊荣</span>
      </div>
      <div className={styles.honors}>
        <Row gutter={[24, 24]}>
          {honors.map((honor, index) => (
            <Col xs={24} sm={12} md={8} key={honor.id || index}>
              <Card className={styles.honorCard} hoverable>
                <div className={styles.honorIcon}>
                  <TrophyOutlined />
                </div>
                <div className={styles.honorContent}>
                  <h3 className={styles.honorName}>{honor.name}</h3>
                  {honor.awardDate && (
                    <div className={styles.honorDate}>
                      <CalendarOutlined /> {dayjs(honor.awardDate).format('YYYY-MM-DD')}
                    </div>
                  )}
                  {honor.description && (
                    <div className={styles.honorDesc}>
                      <p>{honor.description}</p>
                    </div>
                  )}
                </div>
              </Card>
            </Col>
          ))}
        </Row>
        {honorPagination.hasMore && (
          <div className={styles.loadMore}>
            <Button 
              type="link" 
              loading={honorLoading}
              onClick={handleLoadMoreHonors}
            >
              {honorLoading ? '加载中...' : '加载更多'}
            </Button>
          </div>
        )}
      </div>
    </Card>
  );

  return (
    <div className={styles.container}>
      {/* 基本信息部分 */}
      <Card className={styles.section}>
        <Row gutter={[24, 24]}>
          <Col xs={24} md={8}>
            <div className={styles.avatarContainer}>
              <Image
                src={basicInfo?.imageId ? `/api/file/play/${basicInfo.imageId}` : ''}
                alt={basicInfo?.name}
                className={styles.avatar}
                preview={{
                  mask: <EyeOutlined />,
                }}
              />
            </div>
          </Col>
          <Col xs={24} md={16}>
            <div className={styles.infoContent}>
              <div className={styles.nameBlock}>
                <h2>{basicInfo?.name}</h2>
                <div className={styles.subName}>
                  <span className={styles.pinyin}>{basicInfo?.pinyin}</span>
                  <span className={styles.englishName}>{basicInfo?.englishName}</span>
                </div>
              </div>

              <div className={styles.tags}>
                {basicInfo?.occupation && splitString(basicInfo.occupation).map((item) => (
                  <Tag key={item} color="blue">{item}</Tag>
                ))}
              </div>

              <div className={styles.description}>
                {basicInfo?.introduction}
              </div>

              <div className={styles.details}>
                <div className={styles.detailItem}>
                  <CalendarOutlined />
                  <span>生日：{basicInfo?.birthDate}</span>
                </div>
                <div className={styles.detailItem}>
                  <StarOutlined />
                  <span>星座：{basicInfo?.constellation}</span>
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 成长历程 */}
      <Card className={styles.section}>
        <div className={styles.sectionTitle}>
          <HistoryOutlined />
          <span>生涯历程</span>
        </div>
        <div className={styles.career}>
          {renderMilestones()}
        </div>
      </Card>

      {/* 经典语录 */}
      <Card className={styles.section}>
        <div className={styles.sectionTitle}>
          <MessageOutlined />
          <span>经典语录</span>
        </div>
        <Row gutter={[16, 16]}>
          {quotes.map((quote, index) => (
            <Col xs={24} md={12} key={quote.id || index}>
              <div className={styles.quote}>
                <div className={styles.quoteContent}>"{quote.quote}"</div>
                <div className={styles.quoteSource}>—— {quote.famousPersonName}</div>
              </div>
            </Col>
          ))}
        </Row>
        {quotes.length > 0 && quotes.length < quotePagination.total && (
          <div className={styles.loadMore}>
            <Button
              type="link"
              loading={quoteLoading}
              onClick={() => fetchQuotes(quotePagination.current + 1)}
            >
              加载更多
            </Button>
          </div>
        )}
      </Card>

      {/* 荣誉 */}
      {renderHonors()}

      {/* 兴趣爱好 */}
      <Card className={styles.section}>
        <div className={styles.sectionTitle}>
          <HeartOutlined />
          <span>特长</span>
        </div>
        <Row gutter={[24, 24]}>
          {hobbies.map((hobby) => (
            <Col xs={24} sm={12} md={8} key={hobby.name}>
              <div className={styles.hobbyItem}>
                <div className={styles.hobbyIcon}>{hobby.icon}</div>
                <div className={styles.hobbyInfo}>
                  <div className={styles.hobbyName}>{hobby.name}</div>
                  <div className={styles.hobbyDesc}>{hobby.description}</div>
                </div>
              </div>
            </Col>
          ))}
        </Row>
      </Card>

      {/* 视频播放弹窗 */}
      <Modal
        title={null}
        open={videoModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
        centered
        destroyOnClose
        className={styles.videoModal}
      >
        <ReactPlayer
          url={currentVideo}
          controls
          width="100%"
          height="100%"
          playing
          config={{
            file: {
              attributes: {
                controlsList: 'nodownload',
                disablePictureInPicture: true,
              },
            },
          }}
        />
      </Modal>
    </div>
  );
};

export default ProfilePage;
